<template>
  <div class="user-info-container">
    <div class="header">
      <h2>个人信息</h2>
      <el-button type="primary" @click="showEditDialog = true">编辑资料</el-button>
    </div>

    <el-card class="info-card">
      <div class="info-section">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户名">{{ userInfo.username || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ userInfo.email || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ userInfo.phone || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ userInfo.realName || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="账户状态">
            <el-tag :type="userInfo.userAccountStatus?.code === 1 ? 'success' : 'danger'">
              {{ getUserStatusText(userInfo.userAccountStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ formatDate(userInfo.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="最后更新">{{ formatDate(userInfo.updatedAt) }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="action-section">
        <el-button type="warning" @click="showChangePasswordDialog = true">修改密码</el-button>
        <el-button type="danger" @click="handleLogout">退出登录</el-button>
      </div>
    </el-card>

    <!-- 编辑资料对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑资料" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" :disabled="true" />
          <div class="form-tip">用户名创建后不可修改</div>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateProfile" :loading="updating">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showChangePasswordDialog" title="修改密码" width="500px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password placeholder="请输入当前密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="请输入新密码（至少8位，包含大小写字母和数字）" />
          <div class="password-strength">
            <div class="strength-bar" :class="passwordStrengthClass"></div>
            <div class="strength-text">{{ passwordStrengthText }}</div>
          </div>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showChangePasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserInfo, updateProfile, changePassword, logout } from '@/api/userApi'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia'

const router = useRouter()
const userStore = useUserStore()

const userInfo = ref({})
const showEditDialog = ref(false)
const showChangePasswordDialog = ref(false)
const updating = ref(false)
const changingPassword = ref(false)
const editFormRef = ref()
const passwordFormRef = ref()

// 表单数据
const editForm = reactive({
  username: '',
  email: '',
  phone: '',
  realName: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const editRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 计算密码强度
const passwordStrength = computed(() => {
  const password = passwordForm.newPassword
  if (!password) return 0

  let strength = 0
  if (password.length >= 8) strength += 1
  if (/[A-Z]/.test(password)) strength += 1
  if (/[a-z]/.test(password)) strength += 1
  if (/\d/.test(password)) strength += 1
  if (/[^A-Za-z0-9]/.test(password)) strength += 1

  return strength
})

// 密码强度文本
const passwordStrengthText = computed(() => {
  const strength = passwordStrength.value
  if (strength === 0) return ''
  if (strength <= 2) return '弱'
  if (strength === 3) return '中等'
  return '强'
})

// 密码强度样式
const passwordStrengthClass = computed(() => {
  const strength = passwordStrength.value
  if (strength === 0) return ''
  if (strength <= 2) return 'weak'
  if (strength === 3) return 'medium'
  return 'strong'
})

// 密码表单验证规则 - 添加全面的密码校验
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少8位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!/[A-Z]/.test(value)) {
          callback(new Error('密码必须包含至少一个大写字母'))
        } else if (!/[a-z]/.test(value)) {
          callback(new Error('密码必须包含至少一个小写字母'))
        } else if (!/\d/.test(value)) {
          callback(new Error('密码必须包含至少一个数字'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 监听新密码变化，实时显示强度
watch(() => passwordForm.newPassword, (newVal) => {
  // 当新密码变化时，重置确认密码的校验状态
  if (passwordForm.confirmPassword && passwordFormRef.value) {
    passwordFormRef.value.validateField('confirmPassword')
  }
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取用户状态文本
const getUserStatusText = (status) => {
  if (!status) return '未知'
  return status.code === 1 ? '正常' : '禁用'
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const response = await getUserInfo()
    userInfo.value = response
    // 填充编辑表单
    Object.assign(editForm, {
      username: response.username || '',
      email: response.email || '',
      phone: response.phone || '',
      realName: response.realName || ''
    })
  } catch (error) {
    ElMessage.error('获取用户信息失败: ' + (error.message || '未知错误'))
  }
}

// 更新个人资料
const handleUpdateProfile = async () => {
  try {
    await editFormRef.value.validate()
    updating.value = true

    const response = await updateProfile(editForm)
    userInfo.value = response
    userStore.setUserInfo(response)

    ElMessage.success('资料更新成功')
    showEditDialog.value = false
  } catch (error) {
    const errorMsg = error.response?.data?.message || error.message || '更新失败'
    ElMessage.error('更新失败: ' + errorMsg)
  } finally {
    updating.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true

    // 发送修改密码请求
    await changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })

    ElMessage.success('密码修改成功，请重新登录')

    // 清空表单
    Object.keys(passwordForm).forEach(key => {
      passwordForm[key] = ''
    })
    showChangePasswordDialog.value = false

    // 密码修改成功后直接清除本地状态并跳转
    userStore.clearUser()
    ElMessage.success('密码修改成功，请重新登录')
    router.push('/login')

  } catch (error) {
    let errorMsg = '密码修改失败'

    if (error.response) {
      const responseData = error.response.data
      if (responseData && responseData.message) {
        errorMsg = responseData.message
      }
    } else if (error.message) {
      errorMsg = error.message
    }

    ElMessage.error(errorMsg)
  } finally {
    changingPassword.value = false
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      type: 'warning'
    })

    try {
      // 尝试调用退出登录接口
      await logout()
    } catch (error) {
      // 如果退出接口不存在（404），忽略错误，继续执行清除本地状态
      if (error.response && error.response.status === 404) {
        console.log('退出登录接口不存在，继续清除本地状态')
      } else {
        throw error
      }
    }

    // 清除本地用户状态
    userStore.clearUser()
    ElMessage.success('退出成功')
    router.push('/login')
  } catch (error) {
    if (error === 'cancel') return

    // 即使退出API调用失败，也清除本地状态
    userStore.clearUser()
    router.push('/login')
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.user-info-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.info-card {
  margin-bottom: 20px;
}

.info-section {
  margin-bottom: 30px;
}

.info-section h3 {
  margin-bottom: 15px;
  color: #333;
}

.action-section {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.password-strength {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

.strength-bar {
  height: 6px;
  border-radius: 3px;
  margin-right: 10px;
  flex-grow: 1;
  background-color: #e0e0e0;
}

.strength-bar.weak {
  background-color: #ff4d4f;
  width: 33%;
}

.strength-bar.medium {
  background-color: #faad14;
  width: 66%;
}

.strength-bar.strong {
  background-color: #52c41a;
  width: 100%;
}

.strength-text {
  font-size: 12px;
  color: #666;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
  width: 100px;
}
</style>